package com.example.kuaizu.service.imp;

import com.example.kuaizu.mapper.OliveBranchMapper;
import com.example.kuaizu.mapper.TalentMapper;
import com.example.kuaizu.mapper.UserMapper;
import com.example.kuaizu.pojo.UserProfile;
import com.example.kuaizu.pojo.ov.OliveBranchVo;
import com.example.kuaizu.pojo.ov.ProjectInterestedOv;
import com.example.kuaizu.pojo.pram.CreateTalentParam;
import com.example.kuaizu.pojo.pram.GetTalentParam;
import com.example.kuaizu.pojo.pram.TalentReviewParam;
import com.example.kuaizu.pojo.pram.deliveryOliveBranchParam;
import com.example.kuaizu.service.InProjectService;
import com.example.kuaizu.service.InTalentService;
import com.example.kuaizu.utils.ThreadLocalUtil;
import com.example.kuaizu.utils.UserUtils;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import kuaizu.common.PageData;
import kuaizu.common.constp.KuaiZuConst;
import kuaizu.common.exception.MassageException;
import kuaizu.common.tablepojo.OliveBranch;
import kuaizu.common.tablepojo.TalentDB;
import kuaizu.common.tablepojo.TalentReview;
import kuaizu.common.vo.TalentListVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @author: wangmx15
 * @date: 2025/9/18
 **/
@Service
@Log4j2
@RequiredArgsConstructor
public class TalentService implements InTalentService {
    private final TalentMapper talentMapper;
    private final UserMapper userMapper;
    private final OliveBranchMapper oliveBranchMapper;
    private final InProjectService projectService;

    /**
     * 创建人才
     *
     * @param req
     */
    @Override
    @Transactional
    public void createTalent(CreateTalentParam req) {
        Date date = new Date();
        Map<String, Object> map = ThreadLocalUtil.get();
        String openid = map.get("openid").toString();
        TalentListVo vo = talentMapper.queryTalentInfoByOpenId(openid, false);
        if (!ObjectUtils.isEmpty(vo)) {
            if (!KuaiZuConst.TALENT_DELETE.equals(vo.getStatus())) {
                if (!KuaiZuConst.TALENT_CHECK_NO.equals(vo.getStatus())) {
                    throw new MassageException("已经创建过人才");
                }
            }

        }
        if (ObjectUtils.isEmpty(req.getUserInfo())) {
            //根据openid查询用户信息
            if (ObjectUtils.isEmpty(userMapper.selectUserByAppid(openid))) {
                throw new MassageException("用户不存在");
            }
        } else {
            //判断用户传递的信息是否是无用信息
            UserProfile user = new UserProfile();
            BeanUtils.copyProperties(req.getUserInfo(), user);
            user.setOpenid(openid);
            user.setUpdatedAt(date);
            user.setProjectOrientation(req.getUserInfo().getProjectOrientation().getDesc());
            userMapper.updateUser(user);
        }
        TalentDB talent = new TalentDB();
        BeanUtils.copyProperties(req, talent);
        talent.setOpenid(openid);
        talent.setCreateTime(date);
        talent.setJoinProject(req.getJoinProject().toString());
        talent.setStatus(KuaiZuConst.TALENT_NO_CHECK);
        if (ObjectUtils.isEmpty(vo)) {
            talentMapper.insertTalent(talent);
        } else {
            if (null != vo.getId()) {
                talent.setId(vo.getId());
            }
            talentMapper.updateTalent(talent);
        }
    }

    /**
     * 查询所有人才
     *
     * @param req
     * @return
     */

    @Override
    @Transactional
    public PageData<TalentListVo> getTalent(GetTalentParam req) {
        PageMethod.startPage(req.getPageNum(), req.getPageSize());
        PageData<TalentListVo> data = new PageData<>();
        List<TalentListVo> list = new ArrayList<>();
        try {
            list = talentMapper.getTalentList(req);
        } finally {
            PageMethod.clearPage();
        }
        if (CollectionUtils.isEmpty(list)) {
            throw new MassageException("没有数据");
        }
        PageInfo<TalentListVo> pageInfo = new PageInfo<>(list);
        data.setTotal(pageInfo.getTotal());
        data.setPageNum(pageInfo.getPageNum());
        data.setPageSize(pageInfo.getPageSize());
        data.setData(pageInfo.getList());
        return data;
    }

    /**
     * 查看自己的人才信息
     *
     * @return
     */
    @Override
    @Transactional
    public TalentListVo myTalentInfo() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String openid = map.get("openid").toString();
        return talentMapper.queryTalentInfoByOpenId(openid, false);
    }

    /**
     * 删除人才信息
     * @return
     */
    @Override
    @Transactional
    public void deleteMyTalent() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String openid = map.get("openid").toString();
        talentMapper.updateMyTalentStatus(openid);
    }

    /**
     * 获取当前登陆用户的橄榄枝数量
     *
     * @return
     */
    @Override
    @Transactional
    public OliveBranchVo getOliveBranch() {
        Map<String, Object> map = ThreadLocalUtil.get();
        String openid = map.get("openid").toString();
        OliveBranch ob = talentMapper.queryOliveBranchCont(openid);
        OliveBranchVo vo = new OliveBranchVo();
        BeanUtils.copyProperties(ob, vo);
        vo.setOpenid(openid);
        vo.setCount(ob.getGratisCount() + ob.getPurchasesCount());
        return vo;
    }

    @Override
    @Transactional
    public void deliveryOliveBranch(deliveryOliveBranchParam req) {
        Date date = new Date();
        Map<String, Object> map = ThreadLocalUtil.get();
        String openid = map.get("openid").toString();
        //查询橄榄枝的次数
        OliveBranchVo oliveBranchVo = oliveBranchMapper.selectByOpenId(openid);
        if (oliveBranchVo.getCount() <= 0) {
            throw new MassageException("没有可用的橄榄枝");
        }
        //查询是否投递自己投递自己
        TalentListVo vo = talentMapper.queryTalentInfoByOpenId(openid, true);
        if (null == vo) {
            throw new MassageException("人才异常");
        }
        if (vo.getId().equals(req.getTalentId())) {
            throw new MassageException("不能投递自己");
        }
        TalentReview talentReview = new TalentReview();
        talentReview.setOpenid(openid);
        talentReview.setTalentId(req.getTalentId());
        talentReview.setProjectId(req.getProjectId());
        talentReview.setReviewTime(date);
        talentReview.setIsApproved(KuaiZuConst.NOCHECK.toString());
        if (oliveBranchVo.getGratisCount() - 1 >= 0) {
            oliveBranchMapper.updateMyoliveBranchGratisCount(openid);
        } else {
            oliveBranchMapper.updateMyoliveBranchPurchasesCount(openid);
        }
        //插入到人才审核表
        talentMapper.insertTalentReview(talentReview);
    }

    /**
     * 重置每天的橄榄枝数量
     */
    @Override
    @Transactional
    public void oliveBranchResetEveryDay() {
        //查询没有橄榄枝表没有用户的细腻系 获取所有的键
        Map<String, String> map = oliveBranchMapper.selectNotOlivBranch();
        if (!CollectionUtils.isEmpty(map)) {
            Set<String> openid = map.keySet();
            //将获取的键批量添加到数据库中
            int count = oliveBranchMapper.insertOliveBranchs(openid);
            if (count != openid.size()) {
                throw new MassageException("添加失败");
            }
        }
        oliveBranchMapper.oliveBranchResetEveryDay();
    }

    @Override
    @Transactional
    public List<ProjectInterestedOv> getInterestedByMy() {
        return talentMapper.queryProjectByOpenId(UserUtils.getOpenId());
    }

    /**
     * 项目审核
     *
     * @param req
     */
    @Override
    @Transactional
    public void talentReview(TalentReviewParam req) {
        Date date = new Date();
        TalentReview tr = talentMapper.queryTalentReviewById(req.getId());
        if (ObjectUtils.isEmpty(tr)) {
            throw new MassageException("信息错误");
        }
        tr.setReviewTime(date);
        if (req.getStatus()) {
            //审核通过
            tr.setIsApproved(KuaiZuConst.PROJECT_CHECK_PASS.toString());
        } else {
            //审核拒绝
            tr.setIsApproved(KuaiZuConst.PROJECT_CHECK_NO.toString());
        }
        //更新人才审核表
        talentMapper.updateTalentReview(tr);
        //投递项目并且审核通过
        if (req.getStatus()) {
            projectService.joinProject(tr.getProjectId());
            //审核通过项目
            projectService.projectReview(tr.getProjectId(), UserUtils.getOpenId());
        }
    }


}
